package jp.co.cyberagent.android.gpuvideo.sample.activity

import android.app.Activity
import android.content.Intent
import android.media.AudioManager
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.SeekBar
import jp.co.cyberagent.android.gpuimage.filter.GPUImageFilter
import jp.co.cyberagent.android.gpuvideo.sample.R
import jp.co.cyberagent.android.gpuvideo.GPUVideoMediaView
import jp.co.cyberagent.android.gpuvideo.sample.GPUImageFilterTools
import java.io.IOException

class VideoActivity : Activity() {

    private val mediaPlayer: MediaPlayer by lazy {
        MediaPlayer()
    }
    private var filterAdjuster: GPUImageFilterTools.FilterAdjuster? = null
    private val gpuVideoView by lazy { findViewById<GPUVideoMediaView>(R.id.gpuimage) }
    private val seekBar: SeekBar by lazy { findViewById(R.id.seekBar) }

    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_video)
        mediaPlayer.isLooping = true
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC)

        gpuVideoView.setDataSource(mediaPlayer)

        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                filterAdjuster?.adjust(progress)
                gpuVideoView.requestRender()
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

        findViewById<View>(R.id.button_choose_filter).setOnClickListener {
            GPUImageFilterTools.showDialog(this) { filter ->
                switchFilterTo(filter)
                gpuVideoView.requestRender()
            }
        }
        findViewById<View>(R.id.button_save).setOnClickListener { saveVideo() }

        startPhotoPicker()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
            REQUEST_PICK_IMAGE -> if (resultCode == RESULT_OK) {
                try {
                    if (mediaPlayer.isPlaying) {
                        mediaPlayer.stop()
                    }
                    mediaPlayer.setDataSource(this, data!!.data!!)
                    mediaPlayer.prepare()
                    mediaPlayer.start()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            } else {
                try {
                    if (mediaPlayer.isPlaying) {
                        mediaPlayer.stop()
                    }
                    mediaPlayer.setDataSource(
                        this,
                        Uri.parse("android.resource://" + packageName + "/" + R.raw.test)
                    )
                    mediaPlayer.prepare()
                    mediaPlayer.start()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
            else -> super.onActivityResult(requestCode, resultCode, data)
        }
    }

    private fun startPhotoPicker() {
        val photoPickerIntent = Intent(Intent.ACTION_PICK)
        photoPickerIntent.type = "video/*"
        startActivityForResult(photoPickerIntent, REQUEST_PICK_IMAGE)
    }

    private fun saveVideo() {
//        val fileName = System.currentTimeMillis().toString() + ".jpg"
//        gpuVideoView.saveToPictures("GPUImage", fileName) { uri ->
//            Toast.makeText(this, "Saved: " + uri.toString(), Toast.LENGTH_SHORT).show()
//        }
    }

    private fun switchFilterTo(filter: GPUImageFilter) {
        if (gpuVideoView.filter == null || gpuVideoView.filter.javaClass != filter.javaClass) {
            gpuVideoView.filter = filter
            filterAdjuster = GPUImageFilterTools.FilterAdjuster(filter)
            if (filterAdjuster!!.canAdjust()) {
                seekBar.visibility = View.VISIBLE
                filterAdjuster!!.adjust(seekBar.progress)
            } else {
                seekBar.visibility = View.GONE
            }
        }
    }

    companion object {
        private const val REQUEST_PICK_IMAGE = 1
    }

    override fun onDestroy() {
        super.onDestroy()
        mediaPlayer.release()
        gpuVideoView.release()
    }

}